package com.lang.controller;

import cn.dsna.util.images.ValidateCode;
import com.lang.entity.User;
import com.lang.service.UserService;
import com.lang.service.impl.UserServiceImpl;
import com.lang.utils.*;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;

/*
 * @Date : 2024/3/12 16:07
 * @Created by Lang
 * @ProjectName : LclShop
 */
@WebServlet("/user")
public class UserServlet extends BaseServlet {

    public static UserService userService = new UserServiceImpl();

    //校验用户名
    public String getUserByName(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        return userService.getUserByName(username);
    }

    //注册
    public String register(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException, InvocationTargetException, IllegalAccessException {

        //可以将客户端参数名与值注入到Map集合中匹配键值对
        //{u_name=ls,u_password=1,u_email=eadolhp@163.com...}
        Map<String, String[]> map = req.getParameterMap();
        //需要将Map集合的数据注入到User实体中---BeanUtils工具类(反射)
        //注意: Map的属性名要与实体属性名一致,才能注入值
        User user = new User();
        BeanUtils.populate(user,map); //map的数据注入到user实体

        user.setU_password(MD5Utils.md5(user.getU_password())); //密码加密
        user.setU_code(RandomUtils.createActive());  //生成激活码-日期拼接
        user.setU_role(0); //0-普通会员,1-管理员
        user.setU_status(0); //激活状态: 0-未激活  1-已激活
        int res = userService.addUser(user); //注册功能
        System.out.println("注册:"+res);
        if(res>0){
            EmailUtils.sendEmail(user);  //发送邮件
            return StrUtils.REDIRECT+"/registerSuccess.jsp";
        }else{
            req.setAttribute("msg","注册失败");
            return StrUtils.FORWARD+"/message.jsp";
        }
    }

    //验证状态码激活
    public String reCode(HttpServletRequest req, HttpServletResponse resp) {
        String c = req.getParameter("c");
        c = Base64Utils.decode(c);
        User user = userService.getUserByCode(c); //根据激活码对象
        if(user!=null){  //根据激活码可以返回用户对象
            if(user.getU_status()==0){ //没有激活过,可以激活
                int res = userService.updateUserStatus(user.getU_id());
                System.out.println("激活状态" + res);

                req.setAttribute("msg","激活成功!");
            }else if(user.getU_status()==1){//已经激活,不要重复激活
                req.setAttribute("msg","已经激活,不要重复激活");
            }
        }else{ //没有找到激活记录
            req.setAttribute("msg","激活失败!");
        }
        return StrUtils.FORWARD+"/message.jsp";
    }

    //验证码展示
    public void validate(HttpServletRequest request,HttpServletResponse response) throws InvocationTargetException, IllegalAccessException, IOException {
        //参数1:宽  参数2:高  参数3:验证码个数  参数4:干扰线数
        ValidateCode validateCode = new ValidateCode(110, 55, 2, 6);
        request.getSession().setAttribute("imgCode",validateCode.getCode());
        validateCode.write(response.getOutputStream());
    }

    //校验验证码
    public String checkCode(HttpServletRequest request,HttpServletResponse response){

        String imgCode = (String) request.getSession().getAttribute("imgCode");
        String code = request.getParameter("code");
        if (imgCode.equalsIgnoreCase(code)){
            return "0";
        }else {
            return "1";
        }
    }

    //登录
    public String login(HttpServletRequest request,HttpServletResponse response) throws InvocationTargetException, IllegalAccessException, IOException {

        String username = request.getParameter("u_name");
        String password = request.getParameter("u_password");
        String auto = request.getParameter("auto");

        User user = userService.login(username,password);
        if (user == null){
            request.setAttribute("msg","登陆失败");
        }else {
            if(user.getU_status()==0){
                request.setAttribute("msg","未激活,请联系管理员");
            }else{
                request.getSession().setAttribute(StrUtils.lOG_USER,user);
                if (auto != null){
                    Cookie cookie = new Cookie(StrUtils.AUTO_USER, user.getU_name() + "-" + user.getU_password());
                    cookie.setMaxAge(60*60*20*14);
                    response.addCookie(cookie);
                }
                //成功,则直接跳到首页
                return StrUtils.REDIRECT+"/index.jsp";
            }
        }
        return StrUtils.FORWARD + "/message.jsp";
    }

    //注销
    public String logOut(HttpServletRequest request,HttpServletResponse response){
        //1. 清除登录凭证
        request.getSession().removeAttribute(StrUtils.lOG_USER);

        //2.清除cookie
        Cookie cookie = new Cookie(StrUtils.AUTO_USER,"");
        cookie.setMaxAge(0);  //设置有效期为0,则表示立即清除
        response.addCookie(cookie);

        return StrUtils.REDIRECT+"/index.jsp";
    }

}
